package net.howson.phil.datahiding.stream;

import java.io.IOException;
import java.io.InputStream;

public class BitWidthInputStream extends InputStream {

	private final int width;
	private final int mask;
	private final InputStream delegate;
	
	private int cursor;
	private int value;
	private boolean ended;
	
	public BitWidthInputStream(int width, InputStream delegate) {
		if (8 % width !=0 || width>8 || width<1) {
			throw new IllegalArgumentException("Invalid width " + width);
		}
		this.delegate = delegate;
		this.width = width;
		
		this.mask = BitWidthStreamUtils.createMask(width);
		cursor = 8;
	}
	
	
	@Override
	public int read() throws IOException {
		if (ended) {
			return -1;
		}
		if (cursor == 8) {
			int i = delegate.read();
			if (i==-1) {
				ended =true;
				return -1;
			}
			value = i;
			cursor = 0;
		}
		final int out = value & mask;
		value = value >>> width;
		cursor += width;
		return out;
	}
	
	@Override
	public void close() throws IOException {
		delegate.close();
		super.close();
	}

}
